package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import com.reggie.entity.ShoppingCart;
import com.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 购物车添加
     */
    @PostMapping("/add")
    public R<ShoppingCart> shopAdd(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart cart = shoppingCartService.shopadd(shoppingCart);
        return R.success(cart);
    }

    /**
     * 查询购物车
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> selectShop(){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        lqw.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        return R.success(shoppingCarts);
    }

    /**
     * 购物车清空
     */
    @DeleteMapping("/clean")
    public R<String> cleanShop(){
        //删除购物车里的所有东西
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(lqw);
        return R.success("清空购物车成功!");
    }

    /**
     * 购物车数量减少
     */
    @PostMapping("/sub")
    public R<ShoppingCart> subShop(@RequestBody ShoppingCart shoppingCart){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        //是菜品时
        lqw.eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId,shoppingCart.getDishId());
        //是套餐
        lqw.eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart shoppingOne = shoppingCartService.getOne(lqw);
        //清楚成0的时候 就直接删除在购物车里了
        shoppingOne.setNumber(shoppingOne.getNumber()-1);
        if(shoppingOne.getNumber()==0){
            shoppingCartService.removeById(shoppingOne);
        }
        shoppingCartService.updateById(shoppingOne);
        return R.success(shoppingOne);
    }
}
